<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>加速</title>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script src="./ball.js"></script>
<script>
  window.onload = function () {
    var oCanvas = document.querySelector("#canvas"),
      oGc = oCanvas.getContext('2d'),
      width = oCanvas.width, height = oCanvas.height,
      ball = new Ball(width / 2, height / 2);
    ball.fill( oGc );


    addEventListener("keydown", function (ev) {
      oGc.clearRect(0, 0, width, height);
      var oEvent = ev || event;
      if(oEvent.keyCode >= 37 && oEvent.keyCode <= 40) {
        ({
          37: (speed) => ball.x -= speed,
          38: (speed) => ball.y -= speed,
          39: (speed) => ball.x += speed,
          40: (speed) => ball.y += speed
        })[oEvent.keyCode](15)
        console.log(oEvent.keyCode)
        checkBorder();
      }
      ball.fill(oGc);
    }, false);

    // 判断边界
    function checkBorder() {
      //碰到左边界
      if ( ball.x < ball.radius ) {
        ball.x = ball.radius;
      }
      //碰到上边界
      else if ( ball.y < ball.radius ) {
        ball.y = ball.radius;
      }
      //碰到右边界
      else if ( ball.x > width - ball.radius ) {
        ball.x = width - ball.radius;
      }
      //碰到下边界
      else if ( ball.y > height - ball.radius ){
        ball.y = height - ball.radius;
      }
    }
  }
</script>
</body>
</html>